from django.contrib import admin
from django.urls import path
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html
from .models import Category, Product, SKU, Banner
from .admin_views import upload_products_from_excel, generate_excel_template

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'sort_order', 'is_active']
    list_editable = ['sort_order', 'is_active']
    search_fields = ['name']

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'category', 'is_active', 'created_at']
    list_filter = ['category', 'is_active']
    search_fields = ['name', 'description']
    actions = ['make_active', 'make_inactive']

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('upload-excel/', self.admin_site.admin_view(upload_products_from_excel), name='product_upload_excel'),
            path('excel-template/', self.admin_site.admin_view(generate_excel_template), name='product_excel_template'),
        ]
        return custom_urls + urls

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_upload_button'] = True
        return super().changelist_view(request, extra_context=extra_context)

    def make_active(self, request, queryset):
        queryset.update(is_active=True)
    make_active.short_description = _('标记为上架')

    def make_inactive(self, request, queryset):
        queryset.update(is_active=False)
    make_inactive.short_description = _('标记为下架')

@admin.register(SKU)
class SKUAdmin(admin.ModelAdmin):
    list_display = ['product', 'name', 'price', 'stock', 'is_active']
    list_filter = ['product', 'is_active']
    search_fields = ['name', 'product__name']
    list_editable = ['price', 'stock', 'is_active']

@admin.register(Banner)
class BannerAdmin(admin.ModelAdmin):
    list_display = ['title', 'sort_order', 'is_active', 'created_at']
    list_editable = ['sort_order', 'is_active']
    search_fields = ['title']